<template>
  <div>
    <!-- 子表格需要选择字段 -->
    <a-row v-if="sonTableList.includes(configKey)" :gutter="16" style="margin-bottom: 15px">
      <a-col :span="3"> 主表的关联字段： </a-col>
      <a-col :span="8">
        <!-- 选从表的关联字段 -->
        <SearchField
          ref="SearchFieldRef"
          @f_setField="s_setFieldFarelafield"
          field="farelafield"
          :value="congfigMap.farelafield"
        />
      </a-col>
    </a-row>

    <!-- 主表需要选择字段 -->
    <a-row v-else-if="mainTableList.includes(configKey)" :gutter="16" style="margin-bottom: 15px">
      <a-col :span="3"> 主表的关联字段： </a-col>
      <a-col :span="8">
        <!-- 选从表的关联字段 -->
        <SearchField
          ref="F_SearchFieldRef"
          @f_setField="s_setFieldFarelafield"
          field="sonrelafield"
          :value="congfigMap.sonrelafield"
        />
      </a-col>
    </a-row>

    <!-- 卡片 -->
    <a-card class="cardArer" bordered hoverable>
      <template slot="title">
        <a-row :gutter="16">
          <a-col :span="6">
            配置：
            <a-select v-model="configKey" style="width: 80%" @change="handleChange">
              <a-select-option v-for="item in configItemList" :key="item.key" :value="item.key">
                {{ item.title }} <a-tag v-show="item.isConfigurItem" color="blue"> 已配置 </a-tag>
              </a-select-option>
            </a-select>
          </a-col>
          <div v-show="configKey">
            <a-col :span="8">
              申请表: <SearchTable @f_setTable="s_setTable" field="apltable" :value="congfigMap.apltable" />
            </a-col>
            <a-col :span="8">
              企业表: <SearchTable @f_setTable="s_setTable" field="enttable" :value="congfigMap.enttable" />
            </a-col>
            <a-col :span="2">
              <a-switch
                v-model="congfigMap.must"
                default-checked
                @change="switchChange"
                checked-children="必填"
                un-checked-children="非必填"
              />
            </a-col>
          </div>
        </a-row>
      </template>
      <!-- 标题 :offset="1" -->
      <a-row :gutter="16" class="cardArer_title">
        <a-col class="filexConter" :span="3"> 申请字段 </a-col>
        <a-col class="filexConter" :span="5"> 企业字段 </a-col>
        <a-col class="filexConter" :span="5"> 默认值 </a-col>
        <a-col class="filexConter" :span="7"> 配置信息 </a-col>
        <a-col class="filexConter" :span="4"> 操作 </a-col>
      </a-row>
      <!-- 拖拽排序区域 -->
      <div class="cardArer_draggable">
        <draggable
          style="width: 99%"
          :group="{ name: 'relationTable' }"
          v-model="congfigMap.mapping"
          v-bind="dragOptions"
          @start="drag = true"
          @end="
            drag = false
            btnShow = true
          "
        >
          <transition-group type="transition" :name="!drag ? 'flip-list' : null">
            <!-- 绑定字段 -->
            <a-row v-for="(fitem, m_index) in congfigMap.mapping" :key="fitem.t" :gutter="16" class="cardArer_field">
              <a-col class="filexConter" :span="3"> {{ fitem.t }} </a-col>
              <a-col class="filexConter" :span="5">
                <SearchField
                  @f_setField="s_setField"
                  :f_treeData="congfigMap.entFieldList"
                  :index="m_index"
                  :value="fitem.b"
                  field="b"
                />
              </a-col>
              <a-col class="filexConter" :span="5">
                <a-input v-model="fitem.default" placeholder="请输入默认值" />
              </a-col>
              <a-col class="filexConter" :span="7">
                <!-- 显示配置标签 -->
                <a-tag v-show="fitem.isRequired" color="blue"> 必填 </a-tag>
                <a-tag v-if="fitem.isLable" color="pink"> 小标题 </a-tag>
                <a-tag v-if="fitem.type == 'input'" color="green"> 文本 </a-tag>
                <a-tag v-else-if="fitem.type == 'number'" color="green"> 数字 </a-tag>
                <a-tag v-else-if="fitem.type == 'select'" color="green"> 枚举 </a-tag>
                <a-tag v-else-if="fitem.type == 'file'" color="green"> 文件 </a-tag>
                <a-tag v-else-if="fitem.type == 'date'" color="green"> 日期 </a-tag>
                <a-tag v-else-if="fitem.type == 'textarea'" color="green"> 文本域 </a-tag>
                <a-tag v-else-if="fitem.type == 'cascader'" color="green"> 地址级联 </a-tag>
                <a-tag v-else-if="fitem.type == 'tree'" color="green"> 下拉树 </a-tag>
                <a-tag v-if="fitem.isExpression" color="purple"> 响应式 </a-tag>
                <a-tag v-if="fitem.hidden"> 隐藏 </a-tag>
                <a-tag v-if="fitem.disable"> 禁用 </a-tag>
              </a-col>
              <a-col class="filexConter" :span="2">
                <a v-if="fitem.b" @click="handEdit(m_index)" href="javascript:void(0);">
                  <span v-if="fitem.isConfigur"> 已配置 </span>
                  <span v-else style="color: red"> 未配置 </span>
                </a>
              </a-col>
            </a-row>
          </transition-group>
        </draggable>
      </div>
    </a-card>

    <!-- 属性配置组件 -->
    <AttributeModal :f_CongfigMap="congfigMap" @f_setAttribute="s_setAttribute" ref="AttributeRef"></AttributeModal>
  </div>
</template>

<script>
import { findTable } from '@/api/base/table.js'
import { DATA_BASE_SFAPPROVE } from '@/store/mutation-types.js'
import draggable from 'vuedraggable'
export default {
  props: {
    // 需要的配置项列表 [{ name: '通用组件', key: 'GENERAL', isConfigurItem: false }]
    configItemList: {
      type: Array,
      require: true,
    },
    f_congfigMap: {
      type: Object,
    },
  },

  data() {
    return {
      sonTableList: ['STORE', 'LABAPP', 'PLANTEQU'], // 从表key
      mainTableList: ['FAC', 'LAB', 'PLANT', 'PLANTFUNC'], // 从表key
      configKey: undefined,
      btnShow: false,
      drag: false,
      congfigMap: this.f_congfigMap || this.dataInit(),
      // {
      //   enttable: '',
      //   apltable: '',
      //   entFieldList: [],
      //   mapping: [],
      //   farelafield: '', // 配置从表时的关联字段
      //   sonrelafield: '', // 配置主表时的关联字段
      // }
    }
  },
  created() {
    if(this.congfigMap.must == undefined) {
      this.$set(this.congfigMap, 'must', true)
    }
    this.configKey = this.configItemList[0].key
    //如果配置了, 回显vueX配置
    if (this.$store.state.com_config.originalObj[this.configKey] != null) {
      this.congfigMap = this.$store.state.com_config.originalObj[this.configKey]
    }
  },
  computed: {
    dragOptions() {
      return {
        animation: 200,
        group: 'description',
        disabled: false,
        ghostClass: 'ghost',
      }
    },
  },
  methods: {
    // 是否必填
    switchChange(value) {
      // console.log('value', value)
      console.log('value', value, this.congfigMap.must)

    },
    // 从表关联字段回调
    s_setFieldFarelafield(value, field) {
      this.congfigMap[field] = value
    },
    // 配置项下拉
    handleChange(value) {
      // 如果配置了取配置了的对象
      let getObj = this.$store.getters.getOriginalObj(value)
      console.log('回显getObj', getObj)
      if (getObj != null) {
        this.congfigMap = getObj
      } else {
        this.congfigMap = this.dataInit()
      }
    },
    dataInit() {
      return {
        enttable: '',
        apltable: '',
        entFieldList: [],
        mapping: [],
        must: true,
      }
    },
    // 父组件获取当前配置的key
    f_reset() {
      this.congfigMap = this.dataInit()
      return this.configKey
    },
    // 父组件获取配置值
    f_getConfig() {
      let g_check = { status: false, value: this.congfigMap, key: this.configKey }
      if (!this.congfigMap.enttable) {
        this.$message.warning('企业表不能为空')
        return g_check
      }
      if (this.congfigMap.mapping.length == 0) {
        this.$message.warning('配置不能为空')
        return g_check
      }
      // 从表多校验一个关联字段
      if (this.sonTableList.includes(this.configKey) && !this.congfigMap.farelafield) {
        this.$message.warning('请选择从表的关联字段')
        return g_check
      }
      // 从表多校验一个关联字段
      if (this.mainTableList.includes(this.configKey) && !this.congfigMap.sonrelafield) {
        this.$message.warning('请选择主表的关联字段')
        return g_check
      }
      for (let v of this.congfigMap.mapping) {
        if (v.b && v.isConfigur == false) {
          this.$message.warning(`请完成${v.t}的配置`)
          return g_check
        }
      }
      g_check.status = true
      // 把当前的配置项改为已配置
      for (let v of this.configItemList) {
        if (v.key == this.configKey) {
          v.isConfigurItem = true
          break
        }
      }
      return g_check
    },
    // 属性配置子组件返回
    s_setAttribute(attributeObj, attributeValue, index) {
      // console.log('属性配置', attributeObj, attributeValue, index)
      for (let key in attributeObj) {
        this.congfigMap.mapping[index][key] = attributeObj[key]
      }
      this.congfigMap.mapping[index].attributeValue = {}
      this.congfigMap.mapping[index].attributeValue = attributeValue

      // 改成已配置
      this.congfigMap.mapping[index].isConfigur = true
    },
    // 字段配置属性编辑
    handEdit(m_index) {
      // console.log('配置', this.congfigMap.mapping[m_index])
      const title = `${this.congfigMap.mapping[m_index].t} - ${this.congfigMap.mapping[m_index].comments}`
      this.$refs.AttributeRef.f_init(m_index, this.congfigMap, title)
    },
    // 子组件字段选定保存
    s_setField(value, field, index, f_index) {
      console.log('字段绑定', value, field, index, f_index)
      this.$set(this.congfigMap.mapping[index], field, value)
      // this.congfigMap.mapping[index][field] = value
    },
    // 查询申请企业名称的字段
    findAplField(enttable) {
      findTable({ database: DATA_BASE_SFAPPROVE, tableName: enttable }).then((res) => {
        console.log('数据表字段', res)
        if (res.code == 0) {
          this.congfigMap.mapping = []
          res.data.data.forEach((v) => {
              this.congfigMap.mapping.push({
                comments: v.fieldDescription,
                t: v.fieldName,
                b: undefined,
                default: undefined,
                isLable: false, // 是否是小标题
                isRequired: true, // 是否必填
                hidden: false, // 是否必填
                disable: false, // 是否禁用
                type: undefined, // 控件类型
                isExpression: false, // 是否响应式
                attributeValue: {
                  rules: [],
                },
                isConfigur: false,
              })
            })
        }
      })
    },
    findEntField(apltable, index) {
      findTable({ database: DATA_BASE_SFAPPROVE, tableName: apltable }).then((res) => {
        if (res.code == 0) {
          this.congfigMap.entFieldList = []
          let fieldMap = {} // 申请表和企业表同名字段默认回显
          res.data.data.forEach((v) => {
              this.congfigMap.entFieldList.push({
                title: `${v.fieldName} - ${v.fieldDescription}`,
                value: v.fieldName,
              })
              fieldMap[v.fieldName] = v.fieldName
            })
          this.congfigMap.mapping.forEach((v) => {
            if (v.t in fieldMap) {
              v.b = fieldMap[v.t]
              // console.log('v', v)
            }
          })
        }
      })
    },
    // 回显选中的表
    s_setTable(value, field, index) {
      this.congfigMap[field] = value
      // 如果点了清除按钮, 不做处理
      if (!value) {
        return
      }
      if (field == 'apltable') {
        // 通知父组件改变
        this.findAplField(value, index)
        // 刷新关联字段选择表
        if (this.mainTableList.includes(this.configKey)) {
          this.$refs.F_SearchFieldRef.f_init(DATA_BASE_SFAPPROVE, value)
        } else if (this.sonTableList.includes(this.configKey)) {
          this.$refs.SearchFieldRef.f_init(DATA_BASE_SFAPPROVE, value)
        }
      } else if (field == 'enttable') {
        this.findEntField(value, index)
      }
    },
  },
  components: {
    SearchTable: () => import('@/views/businessAssembly/public/spareparts/searchTable'),
    SearchField: () => import('@/views/businessAssembly/public/spareparts/searchField'),
    AttributeModal: () => import('@/views/businessAssembly/public/spareparts/attributeModal'),
    draggable,
  },
}
</script>

<style lang="less" scoped>
.btnBox {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 30px;
  padding-bottom: 50px;
}
.cardArer {
  // border: 1px solid red;
  &_title {
    background-color: rgb(247, 247, 247);
    font-weight: 800;
  }
  &_field {
    background-color: rgb(255, 250, 240);
    border-bottom: 1px solid rgb(238, 238, 238);
  }
  &_draggable {
    // border: 1px solid red;
    max-height: 350px;
    overflow: auto;
  }
}
.filexConter {
  height: 50px;
  display: flex;
  align-items: center;
  // border: 1px solid blue;
}
</style>
